﻿using Infragistics.Win.UltraMessageBox;
using OrBitDataModule.Contract;
using OrBitDataModule.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace OrBitDataModule.Dialog
{
    public partial class AddScript : Form
    {
        private readonly bool IsEdit;
        private string DataProtocolScriptId = string.Empty;
        private string ScriptName = string.Empty;
        private string ScriptCode = string.Empty;
        private string ScriptDescription = string.Empty;
        public AddScript(bool isEdit, string dataProtocolScriptId, string scriptName, string scriptCode, string scriptDescription)
        {
            InitializeComponent();
            this.IsEdit = isEdit;
            this.DataProtocolScriptId = dataProtocolScriptId;
            this.ScriptName = scriptName;
            this.ScriptCode = scriptCode;
            this.ScriptDescription = scriptDescription;

            this.Text = IsEdit ? "修改脚本" : "新增脚本";
            this.Load += AddScript_Load;
            this.btn_save.Click += Btn_save_Click;
            this.btn_cancel.Click += Btn_cancel_Click;
        }
        private void AddScript_Load(object sender, EventArgs e)
        {
            if (IsEdit)
            {
                this.ute_ScriptName.Text = ScriptName;
                this.ute_ScriptDescription.Text = ScriptDescription;
            }
        }
        private async void Btn_save_Click(object sender, EventArgs e)
        {
            // 新增时没有脚本代码，给一个默认的脚本代码
            if (string.IsNullOrWhiteSpace(this.ScriptCode))
            {
                this.ScriptCode = Properties.Resource.DefaultScriptCode;
            }
            var result = await ScriptApi.AddScript(this.DataProtocolScriptId, this.ute_ScriptName.Text, this.ScriptCode, this.ute_ScriptDescription.Text);
            UltraMessageBoxManager.Show(this, result.Message, result.Result ? "提示" : "错误", MessageBoxButtons.OK, result.Result ? MessageBoxIcon.Information : MessageBoxIcon.Error);
            if (result.Result) this.Close();
        }
        private void Btn_cancel_Click(object sender, EventArgs e) => this.Close();
    }
}
